package com.m7788.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;

public class FileDownloadUtil {
	private String ALBUM_PATH = Environment.getExternalStorageDirectory()
			.getAbsolutePath() + File.separator + "7788" + File.separator;
	private DownLoadListener mDownLoadListener;
	public interface DownLoadListener{
		public void downLoadSuccess();
	}
	public FileDownloadUtil(DownLoadListener downLoadListener) {
		this.mDownLoadListener = downLoadListener;
	}

	public void downFileFromUrl(Context context,String url) {
		File dirFile = new File(ALBUM_PATH);
		if(!dirFile.exists()){
			dirFile.mkdirs();
		}
		new DownFileThread(context,url).start();
	}

	/*
	 * 连接网络 由于在4.0中不允许在主线程中访问网络，所以需要在子线程中访问
	 */
	private class DownFileThread extends Thread {
		private String url;
		private Context context;
		public DownFileThread(Context context,String url) {
			super();
			this.url = url;
			this.context = context;
		}

		@Override
		public void run() {
			try {
				String[] s = url.split("/");
				String fileName = "";
				if (s.length > 0) {
					fileName = s[s.length - 1];
				}
				// ******** 方法2：取得的是InputStream，直接从InputStream生成bitmap
				// ***********/
				loadImgSaveToLocal(context,url, ALBUM_PATH+fileName);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void loadImgSaveToLocal(final Context context,String url, String filename) {
		try {
			final File file = new File(filename);
			// 得到图片地址
			final byte[] data = readImage(url);
			new Handler(Looper.getMainLooper()).post(new Runnable() {
				
				@Override
				public void run() {
					FileOutputStream outStream;
					try {
						outStream = new FileOutputStream(file);
						outStream.write(data);
						// 关闭流的这个地方需要完善一下
						outStream.close();
						new Handler(Looper.getMainLooper()).post(new Runnable() {
							
							@Override
							public void run() {
								if(mDownLoadListener!=null){
									mDownLoadListener.downLoadSuccess();
								}
							}
						});
						  if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
			                    Intent mediaScanIntent = new Intent(
			                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			                    Uri contentUri = Uri.fromFile(file); //out is your output file
			                    mediaScanIntent.setData(contentUri);
			                    context.sendBroadcast(mediaScanIntent);
			                } else {
			                	context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"    
					                    + Environment.getExternalStorageDirectory())));    
			                }
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 声明称为静态变量有助于调用
	public static byte[] readImage(String path) throws Exception {
		URL url = new URL(path);
		// 记住使用的是HttpURLConnection类
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		// 如果运行超过5秒会自动失效 这是android规定
		conn.setConnectTimeout(5 * 1000);
		InputStream inStream = conn.getInputStream();
		// 调用readStream方法
		return readStream(inStream,conn);
	}

	public static byte[] readStream(InputStream inStream,HttpURLConnection conn) throws Exception {
		// 把数据读取存放到内存中去
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		byte[] bytes = outSteam.toByteArray();
		outSteam.close();
		inStream.close();
		conn.disconnect();
		return bytes;
	}
}
